/* Copyright  2009
   @Author
   Richard Changde Yin            e-mail yinchangde@hotmail.com

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; version 2 of the License.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */
   
/**
 *@filename: item/string.cc
 */ 
#include <server_includes.h>
#include CSTDINT_H
#include <session.h>
#include <error.h>
#include <item/string.h>

Item *Item_string::safe_charset_converter(const CHARSET_INFO * const tocs)
{
  Item_string *conv;
  uint32_t conv_errors;
  char *ptr;
  String tmp, cstr, *ostr= val_str(&tmp);
  cstr.copy(ostr->ptr(), ostr->length(), ostr->charset(), tocs, &conv_errors);
  if (conv_errors || !(conv= new Item_string(cstr.ptr(), cstr.length(),
                                             cstr.charset(),
                                             collation.derivation)))
  {
    /*
      Safe conversion is not possible (or EOM).
      We could not convert a string into the requested character set
      without data loss. The target charset does not cover all the
      characters from the string. Operation cannot be done correctly.
    */
    return NULL;
  }
  if (!(ptr= current_session->strmake(cstr.ptr(), cstr.length())))
    return NULL;
  conv->str_value.set(ptr, cstr.length(), cstr.charset());
  /* Ensure that no one is going to change the result string */
  conv->str_value.mark_as_const();
  return conv;
}


Item *Item_static_string_func::safe_charset_converter
                               (const CHARSET_INFO * const tocs)
{
  Item_string *conv;
  uint32_t conv_errors;
  String tmp, cstr, *ostr= val_str(&tmp);
  cstr.copy(ostr->ptr(), ostr->length(), ostr->charset(), tocs, &conv_errors);
  if (conv_errors ||
      !(conv= new Item_static_string_func(func_name,
                                          cstr.ptr(), cstr.length(),
                                          cstr.charset(),
                                          collation.derivation)))
  {
    /*
      Safe conversion is not possible (or EOM).
      We could not convert a string into the requested character set
      without data loss. The target charset does not cover all the
      characters from the string. Operation cannot be done correctly.
    */
    return NULL;
  }
  conv->str_value.copy();
  /* Ensure that no one is going to change the result string */
  conv->str_value.mark_as_const();
  return conv;
}


bool Item_string::eq(const Item *item, bool binary_cmp) const
{
  if (type() == item->type() && item->basic_const_item())
  {
    if (binary_cmp)
      return !stringcmp(&str_value, &item->str_value);
    return (collation.collation == item->collation.collation &&
            !sortcmp(&str_value, &item->str_value, collation.collation));
            
  }
  return 0;
}

void Item_string::print(String *str, enum_query_type query_type)
{
  if (query_type == QT_ORDINARY && is_cs_specified())
  {
    str->append('_');
    str->append(collation.collation->csname);
  }

  str->append('\'');

  if (query_type == QT_ORDINARY ||
      is_charset_same(str_value.charset(), system_charset_info))
  {
    str_value.print(str);
  }
  else
  {
    Session *session= current_session;
    LEX_STRING utf8_lex_str;

    session->convert_string(&utf8_lex_str,
                        system_charset_info,
                        str_value.c_ptr_safe(),
                        str_value.length(),
                        str_value.charset());

    String utf8_str(utf8_lex_str.str,
                    utf8_lex_str.length,
                    system_charset_info);

    utf8_str.print(str);
  }

  str->append('\'');
}

double Item_string::val_real()
{
  assert(fixed == 1);
  int error;
  char *end, *org_end;
  double tmp;
  const CHARSET_INFO * const cs= str_value.charset();

  org_end= (char*) str_value.ptr() + str_value.length();
  tmp= my_strntod(cs, (char*) str_value.ptr(), str_value.length(), &end,
                  &error);
  if (error || (end != org_end && !check_if_only_end_space(cs, end, org_end)))
  {
    /*
      We can use str_value.ptr() here as Item_string is gurantee to put an
      end \0 here.
    */
    push_warning_printf(current_session,COLLAPSAR_ERROR::WARN_LEVEL_WARN,
                        ER_TRUNCATED_WRONG_VALUE,
                        ER(ER_TRUNCATED_WRONG_VALUE), "DOUBLE",
                        str_value.ptr());
  }
  return tmp;
}

/**
  @todo
  Give error if we wanted a signed integer and we got an unsigned one
*/
int64_t Item_string::val_int()
{
  assert(fixed == 1);
  int err;
  int64_t tmp;
  char *end= (char*) str_value.ptr()+ str_value.length();
  char *org_end= end;
  const CHARSET_INFO * const      cs       = str_value.charset();

  tmp= (*(cs->cset->strtoll10))(cs, str_value.ptr(), &end, &err);
  /*
    TODO: Give error if we wanted a signed integer and we got an unsigned
    one
  */
  if (err > 0 ||
      (end != org_end && !check_if_only_end_space(cs, end, org_end)))
  {
    push_warning_printf(current_session,COLLAPSAR_ERROR::WARN_LEVEL_WARN,
                        ER_TRUNCATED_WRONG_VALUE,
                        ER(ER_TRUNCATED_WRONG_VALUE), "INTEGER",
                        str_value.ptr());
  }
  return tmp;
}

my_decimal *Item_string::val_decimal(my_decimal *decimal_value)
{
  return val_decimal_from_string(decimal_value);
}

int Item_string::save_in_field(Field *field, bool)
{
  String *result;
  result=val_str(&str_value);
  return save_str_value_in_field(field, result);
}



